package com.webapp.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.compress.archivers.ArchiveException;
import org.apache.commons.compress.archivers.ArchiveInputStream;
import org.apache.commons.compress.archivers.ArchiveStreamFactory;
import org.apache.commons.compress.archivers.zip.ZipArchiveEntry;
import org.apache.commons.compress.archivers.zip.ZipArchiveInputStream;
import org.apache.commons.compress.archivers.zip.ZipArchiveOutputStream;
import org.apache.commons.compress.archivers.zip.ZipFile;
import org.apache.commons.compress.compressors.CompressorException;
import org.apache.commons.compress.compressors.CompressorInputStream;
import org.apache.commons.compress.compressors.CompressorStreamFactory;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.IOUtils;

import com.webapp.model.UploadModel;

/**
 * Servlet implementation class Upload
 */
public class UploadPDFS extends HttpServlet {
	private static final long serialVersionUID = 1L; 
	
	private static final String DESTINATION_DIR_PATH ="/pdf";
	private File destinationDir;
	
    /**
     * @see HttpServlet#HttpServlet()
     */
    public UploadPDFS() {
        super();
        // TODO Auto-generated constructor stub
    }

	public void init(ServletConfig config) throws ServletException {
		super.init(config);
		String realPath = getServletContext().getRealPath(DESTINATION_DIR_PATH);
		destinationDir = new File(realPath);
		if(!destinationDir.isDirectory()) {
			boolean createdestinationDir = new File(realPath).mkdir();
		}
 
	}
	
	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException  {
		
		DiskFileItemFactory  fileItemFactory = new DiskFileItemFactory();
		fileItemFactory.setSizeThreshold(3*1024*1024); // file size
		ServletFileUpload uploadHandler = new ServletFileUpload(fileItemFactory);
		File theFile = null;
		List<String> fileDirectories = new ArrayList();
		try {
			List items = uploadHandler.parseRequest(request);
			Iterator itr = items.iterator();
			while(itr.hasNext()) {
				FileItem item = (FileItem) itr.next();
				if(item.isFormField()) {
					System.out.println("ignore:" + item.getFieldName());
				} else {		
			        final InputStream is = item.getInputStream();
			        ArchiveInputStream in = null;
			        try {
			            in = new ArchiveStreamFactory().createArchiveInputStream("zip", is);
			            ZipArchiveEntry entry = null;
			            while((entry = (ZipArchiveEntry)in.getNextEntry()) != null) {
			            	System.out.println("the entry" + entry);
			                File outfile = new File(destinationDir + "/result/" + entry.getName());
			                outfile.getParentFile().mkdirs();
			                System.out.print(outfile.getAbsolutePath());
			                OutputStream o = new FileOutputStream(outfile);
			                try {
			                    IOUtils.copy(in, o);
			                } finally {
			                    o.close();
			                }
			                fileDirectories.add("pdf/"+outfile.getName());
			            }
			        } finally {
			            if (in != null) {
			                in.close();
			            }
			        }
			        is.close();
				}
			}
		}catch(FileUploadException ex) {
			log("Error encountered while parsing the request",ex);
		} catch(Exception ex) {
			log("Error encountered while uploading file",ex);
		}
		
		
		UploadModel um = new UploadModel();
		boolean test = false;
		for( int i = 0; i < fileDirectories.size(); i++) {
			System.out.println("given to model" + fileDirectories.get(i));
			test = um.uploadPDF((String) fileDirectories.get(i));
		}
		
		if(test == true) {
			response.sendRedirect("upload.jsp?upload=true");
		} else {
			response.sendRedirect("upload.jsp?upload=false");
		}
	}
}
